package com.example.administrator.managesystem.activity.my_profile;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.example.administrator.managesystem.R;
import com.example.administrator.managesystem.activity.firstpage.circle.ui.SendCircleActivity;
import com.example.administrator.managesystem.adapter.GoodsGridLandAdapter;
import com.example.administrator.managesystem.base.BaseActivity;
import com.example.administrator.managesystem.bean.GoodsListBean;
import com.example.administrator.managesystem.bean.LandListBean;
import com.example.administrator.managesystem.bean.UploadBean;
import com.example.administrator.managesystem.presenter.profile.GoodsPresenter;
import com.example.administrator.managesystem.ui.GoodsView;
import com.example.administrator.managesystem.utils.AppUtils;
import com.example.administrator.managesystem.utils.GlobalConfig;
import com.example.administrator.managesystem.utils.ShareUtil;
import com.example.administrator.managesystem.utils.ToastUtils;
import com.example.administrator.managesystem.video.LandListActivity;
import com.example.administrator.managesystem.view.MyGridView;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.DateUtils;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.luck.picture.lib.tools.StringUtils;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;
import com.squareup.picasso.Picasso;

import java.io.File;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

public class AddGoodsActivity extends BaseActivity implements GoodsView {
    private EditText goods_name,price,storage;
    private LinearLayout choose_type;
    private RelativeLayout choose_detail,uploadIsTrue,uploadIsFalse;
    private TextView send,add_video,add_image,duration_tv,land_number;
    private GoodsPresenter goodsPresenter;
    private GoodsGridLandAdapter goodsGridLandAdapter;
    private MyGridView gridView;
    private ImageView add_video_iv,add_image_iv,imageIsFalse,videoIsFalse;
    private List<LocalMedia> video_select = new ArrayList<>();
    private List<LocalMedia> image_select = new ArrayList<>();
    private List<String> image_list=new ArrayList<>();
    private String landId;
    private boolean flag;

    @Override
    public void initView() {
        showfloatButton(true,true);
        goods_name=findViewById(R.id.goods_title);
        price=findViewById(R.id.price);
        storage=findViewById(R.id.storage_num);
        choose_type=findViewById(R.id.choose_goods_type);
        choose_detail=findViewById(R.id.type_detail);
        send=findViewById(R.id.send);
        gridView=findViewById(R.id.land_gv);
        uploadIsFalse=findViewById(R.id.uploadIsFalse);
        uploadIsTrue=findViewById(R.id.uploadIsTrue);
        add_image=findViewById(R.id.add_image_tv);
        imageIsFalse=findViewById(R.id.image_preview);
        videoIsFalse=findViewById(R.id.video_player);
        add_video=findViewById(R.id.add_video_tv);
        land_number=findViewById(R.id.land_number);
        add_image.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG );//下划线
        add_image.getPaint().setAntiAlias(true);//抗锯齿
        add_video.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG );//下划线
        add_video.getPaint().setAntiAlias(true);//抗锯齿

        add_video_iv=findViewById(R.id.add_video);
        add_image_iv=findViewById(R.id.add_image);
        duration_tv=findViewById(R.id.tv_duration);
        goodsPresenter=new GoodsPresenter(this);
        goodsGridLandAdapter=new GoodsGridLandAdapter(this);

    }

    @Override
    public void doBusiness() {
      choose_type.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
              choose_detail.setVisibility(View.VISIBLE);
              goodsPresenter.landListRequest(ShareUtil.getUserId(AddGoodsActivity.this),ShareUtil.getUserToken(AddGoodsActivity.this),AddGoodsActivity.this);
          }
      });

      send.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {

              if(video_select.isEmpty() && flag){
                  ToastUtils.showToast(AddGoodsActivity.this,"请上传视频！");
                  return;
              }
              if(image_list.isEmpty() && flag){
                  ToastUtils.showToast(AddGoodsActivity.this,"请上传图片！");
                  return;
              }
              showProgressDialog();
              if(flag){
                  goodsPresenter.sendGoodsRequest(ShareUtil.getUserId(AddGoodsActivity.this),ShareUtil.getUserToken(AddGoodsActivity.this),landId,goods_name.getText().toString(),
                          price.getText().toString(),storage.getText().toString(),video_select.get(0).getPath(),image_list,AddGoodsActivity.this);
              }else{
                  goodsPresenter.sendGoodsRequestOK(ShareUtil.getUserId(AddGoodsActivity.this),ShareUtil.getUserToken(AddGoodsActivity.this),landId,goods_name.getText().toString(),
                          price.getText().toString(),storage.getText().toString(),AddGoodsActivity.this);
              }

          }
      });
    goodsGridLandAdapter.setOnItemClickListener(new GoodsGridLandAdapter.OnItemClickListener() {
        @Override
        public void onItemClick(int position, String land_id,String land_name, View v) {
            landId=land_id;
            choose_detail.setVisibility(View.GONE);
            goodsPresenter.checkVPRequest(ShareUtil.getUserId(AddGoodsActivity.this),land_id,ShareUtil.getUserToken(AddGoodsActivity.this),AddGoodsActivity.this);
            land_number.setText(land_name);

        }
    });

  add_video.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
          // 进入相册 以下是例子：不需要的api可以不写
          PictureSelector.create(AddGoodsActivity.this)
                  .openGallery(PictureMimeType.ofVideo())
                  .maxSelectNum(1)
                  .selectionMode(PictureConfig.SINGLE)
                  .previewVideo(true)
                  .enablePreviewAudio(true) // 是否可播放音频
                  .isCamera(true)
                  .compress(true)
                  .glideOverride(160, 160)
                  .minimumCompressSize(100)// 小于 100kb 的图片不压缩
                  .cropCompressQuality(90)// 裁剪压缩质量 默认100
                  .selectionMedia(video_select)
                  .forResult(PictureConfig.TYPE_VIDEO);
      }
  });

  add_video_iv.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
          if(video_select.isEmpty()){
              ToastUtils.showToast(AddGoodsActivity.this,"请添加视频！");
              return;
          }
          PictureSelector.create(AddGoodsActivity.this).externalPictureVideo(video_select.get(0).getPath());

      }
  });

   add_image.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View v) {
           // 进入相册 以下是例子：不需要的api可以不写
           PictureSelector.create(AddGoodsActivity.this)
                   .openGallery(PictureMimeType.ofImage())
                   .previewImage(true)
                   .maxSelectNum(9)
                   .minSelectNum(1)
                   .selectionMode(PictureConfig.MULTIPLE)
                   .isCamera(true)
                   .compress(true)
                   .glideOverride(160, 160)
                   .minimumCompressSize(100)// 小于 100kb 的图片不压缩
                   .cropCompressQuality(90)// 裁剪压缩质量 默认100
                   .selectionMedia(image_select)
                   .forResult(PictureConfig.TYPE_CAMERA);
       }
   });

   add_image_iv.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View v) {
           if(image_list.isEmpty()){
               ToastUtils.showToast(AddGoodsActivity.this,"请添加图片！");
               return;
           }
           // 预览图片
           PictureSelector.create(AddGoodsActivity.this).externalPicturePreview(0,image_select);
       }
   });
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_add_goods;
    }

    @Override
    public void showLandGrid(List<LandListBean.DataBean> list) {
           goodsGridLandAdapter.addDatas(list);
           gridView.setAdapter(goodsGridLandAdapter);
    }

    @Override
    public void showUpload(final UploadBean.DataBean dataBean) {

        if(dataBean.isUpload()){
            flag=true;
           uploadIsTrue.setVisibility(View.VISIBLE);
           uploadIsFalse.setVisibility(View.GONE);
        }else{
            flag=false;
            uploadIsTrue.setVisibility(View.GONE);
            uploadIsFalse.setVisibility(View.VISIBLE);

            if(dataBean.getImage().getCount()<1){
                imageIsFalse.setVisibility(View.INVISIBLE);
            }
            if(dataBean.getVideo().getCount()<1){
                videoIsFalse.setVisibility(View.INVISIBLE);
            }
            Picasso.with(AddGoodsActivity.this).load(GlobalConfig.ONLINE_HTTP+""+dataBean.getImage().getPath()).into(imageIsFalse);
            imageIsFalse.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent=new Intent(AddGoodsActivity.this,ImageViewActivity.class);
                    intent.putExtra("image_url",dataBean.getImage().getPath());
                    startActivity(intent);
                }
            });

            videoIsFalse.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent=new Intent(AddGoodsActivity.this,VideoPreviewActivity.class);
                    intent.putExtra("video_url",dataBean.getVideo().getPath());
                    startActivity(intent);
                }
            });
        }

    }

    @Override
    public void showDeleteMsg() {
        dismissProgressDialog();
    }

    @Override
    public void showGoodsList(List<GoodsListBean.DataBean> list,int type) {

    }

    @Override
    public void showErrMsg() {

    }

    @Override
    public void showUpdateMsg() {

    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.TYPE_VIDEO:
                    // 视频选择
                    video_select= PictureSelector.obtainMultipleResult(data);
                    Drawable drawable = ContextCompat.getDrawable(AddGoodsActivity.this, R.drawable.video_icon);
                    StringUtils.modifyTextViewDrawable(duration_tv, drawable, 0);
                    duration_tv.setText(DateUtils.timeParse(video_select.get(0).getDuration()));
                    duration_tv.setVisibility(View.VISIBLE);
                    RequestOptions options = new RequestOptions()
                            .centerCrop()
                            .placeholder(R.color.color_f6)
                            .diskCacheStrategy(DiskCacheStrategy.ALL);
                    Glide.with(AddGoodsActivity.this)
                            .load(video_select.get(0).getPath())
                            .apply(options)
                            .into(add_video_iv);
                    Log.e("msg","video_select.get(0).getPath():"+video_select.get(0).getPath());
                    break;
                    case PictureConfig.TYPE_CAMERA:
                           image_list.clear();
                           image_select=PictureSelector.obtainMultipleResult(data);
                        for(int i=0;i<image_select.size();i++){
                            image_list.add(image_select.get(i).getCompressPath());
                        }


                        Log.e("msg","image_select.get(0).getCompressPath():"+image_select.get(0).getCompressPath().length());
                        RequestOptions option = new RequestOptions()
                                .centerCrop()
                                .placeholder(R.color.color_f6)
                                .diskCacheStrategy(DiskCacheStrategy.ALL);
                        Log.e("msg","123444");
                        Glide.with(AddGoodsActivity.this)
                                .load(image_list.get(0))
                                .apply(option)
                                .into(add_image_iv);
                        break;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
           //清理缓存
        PictureFileUtils.deleteCacheDirFile(AddGoodsActivity.this);
    }


}
